#include "TcpServer.hpp"
#include "http.hpp"

void Usage(std::string proc)
{
    std::cout << "Usage: " << proc << " serverport" << std::endl;
}

// 回调处理业务模块
std::shared_ptr<HttpResponse> Login(std::shared_ptr<HttpRequest> request)
{
    LOG(DEBUG, "=========================\n");
    std::string userdata;
    if (request->Method() == "GET")
    {
        userdata = request->Args();
    }
    else if (request->Method() == "POST")
    {
        userdata = request->Text();
    }
    else
    {
    }
    // 1. 进程间通信， 比如 pipe！ 还有环境变量！

    // 2. fork()

    // 3. exec()
    // Java  Python / Php...
    // 处理数据了

    LOG(DEBUG, "enter data handler, data is : %s\n", userdata.c_str());
    auto response = Factory::BuildHttpResponse();
    response->AddStatusLine(200, "OK");
    response->AddHeaderLine("Content-Type", "text/html");
    response->AddText("<html><h1>handler data done</h1></html>");
    LOG(DEBUG, "=========================\n");
    return response;
}

// httpserver  port
int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        Usage(argv[0]);
        exit(USAGE_ERROR);
    }
    uint16_t port = std::stoi(argv[1]);
    HttpServer httpservice;
    // 仿照路径，来进行功能路由！
    httpservice.AddHandler("/login", Login);
    // httpservice.AddHandler("/register", Login);
    // httpservice.AddHandler("/serarch", Search);
    TcpServer tsvr(port, std::bind(&HttpServer::HandlerHttpReqeust, &httpservice, std::placeholders::_1));
    tsvr.Loop();
    return 0;
}
